// pages/upload/uploadPage/index.js
const db = wx.cloud.database()
const tiku = db.collection("shuati")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    subject: [],
    subjectIndex: 0,
    answer: [],
    question: "",
    answer1: "",
    answer2: "",
    answer3: "",
    answer4: "",
    checkBox: [],
    selectSubject: ""
  },



  //上传题目方法
  upload: function (e) {
    var params = e.detail.value
    var pickItems = params.pickItems
    params.pickItems = (pickItems == null ? this.data.subject[0] : this.data.subject[params.pickItems])
    var check = this._checkParams(params)
    if (check) {
      var uploadTitle = new Object()
      var checkBoxs = ""
      if (params.checkBox.length > 1) {
        var checkBox = params.checkBox
        for (let i = 0; i < checkBox.length; i++) {
          checkBoxs += checkBox[i]
          if (i < checkBox.length - 1) {
            checkBoxs += "+"
          }
        }
      }
      uploadTitle = {
        question: params.question,
        answer1: params.answer1,
        answer2: params.answer2,
        answer3: params.answer3,
        answer4: params.answer4,
        checkBox: checkBoxs.length > 1 ? checkBoxs : params.checkBox
      }
      var user = wx.getStorageSync('user')
      console.log("uploadTitle", uploadTitle)
      wx.cloud.database().collection("upload").add({
        data: {
          selectSubject: params.pickItems,
          uploadTitle,
          account: user.account,
          name: user.name
        }
      }).then(res => {
        wx.showToast({
          icon:"success",
          title: '感谢您的上传！',
        })
      }).catch(err => {
        wx.showToast({
          icon:"error",
          title: '上传失败！',
        })
      })
    }
  },

  //检查上传的题库是否符合规则
  _checkParams: function (e) {
    if (e.checkBox.length == 0) {
      wx.showToast({
        icon: "error",
        title: '必须勾选答案',
      })
      return false
    }
    if (e.answer1 == "" || e.answer2 == "" || e.answer3 == "" || e.answer4 == "") {
      wx.showToast({
        icon: "error",
        title: '必须填写选项',
      })
      return false
    }
    if (e.question == "") {
      wx.showToast({
        icon: "error",
        title: '必须填写答案',
      })
      return false
    }
    return true
  },


  //设置科目
  bindPickerChange: function (e) {
    this.setData({
      subjectIndex: e.detail.value,
      selectSubject: this.data.subject[e.detail.value]
    })
    console.log("e", this.data)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    tiku.where({
      name: "kemu"
    }).get().then(res => {
      this.setData({
        subject: res.data[0].subject,
      })
    })
  },
})